package com.example.e_comm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.e_comm.dto.UserDTO;
import com.example.e_comm.entity.User;
import com.example.e_comm.service.UserService;
import jakarta.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/list")
    public List<User> list() {
        return userService.list();
    }

    @GetMapping("/listByPage")
    public IPage<User> listByPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        return userService.pageUsers(new Page<>(pageNum, pageSize));
    }

    @GetMapping("/listByPageWithCondition")
    public IPage<User> listByPageWithCondition(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        return userService.pageUsersWithCondition(new Page<>(pageNum, pageSize), keyword);
    }

    @GetMapping("/{id}")
    public User detail(@PathVariable Long id) {
        return userService.get(id);
    }

    @PostMapping("/create")
    @ResponseStatus(HttpStatus.CREATED)
    public boolean create(@Valid @RequestBody UserDTO dto) {
        if (userService.count(new QueryWrapper<User>().eq("username", dto.getUsername())) > 0) {
            return false;
        }
        if (userService.count(new QueryWrapper<User>().eq("email", dto.getEmail())) > 0) {
            return false;
        }
        return userService.create(dto);
    }

    @PostMapping("/delete/ids")
    public boolean delete(@RequestBody List<Long> ids) {
        return userService.removeByIds(ids);
    }

    //===============================================================================================
    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User  user){
        try{
            boolean result = userService.register(user);
            if ( result){
                return ResponseEntity.ok("注册成功");
            }else {
                return ResponseEntity.ok("注册失败");
            }
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    //用户登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username, @RequestParam String password){
        try{
            String token = userService.login(username, password);
            Map<String, String> response = new HashMap<>();
            response.put("token", token);
            response.put("message", "登录成功");
            return ResponseEntity.ok(response);
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    //当前用户信息
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token){
        Logger logger = LoggerFactory.getLogger(UserController.class);
        logger.info("当前用户信息：{}", userService.getUserByToken(token));
        try{
            String clean = token.replace("Bearer ", "");
            logger.info("当前用户信息：{}", userService.getUserByToken(clean));
            User user = userService.getUserByToken(clean);
            if (user != null){
                user.setPassword(null);
                return ResponseEntity.ok(user);
            }else {
                logger.warn("没有找到用户Token");
                return ResponseEntity.status(401).body("没有找到用户Token,或已Token过期");
            }
        }catch (Exception e){
            logger.error("请求错误：", e);
            return ResponseEntity.status(400).body("请求错误" + e.getMessage());
        }
    }
    //退出登录
    @GetMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader("Authorization") String token){
        try{
            boolean result = userService.logout(token.replace("Bearer ", ""));
            if (result){
                return ResponseEntity.ok("注销成功");
            }else {
                return ResponseEntity.ok("注销失败");
            }
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}